package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.user.dtos.AppLoginDto;
import com.heima.model.user.dtos.UserInfoDto;
import com.heima.user.entity.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-03-01
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private BCryptPasswordEncoder encoder;

    //app端用户登录
    @Override
    public Map<String,Object> login(AppLoginDto dto) {
        Map<String,Object> result = new HashMap<>();
        int userId = 0;
        //1. 判断是否手机号密码登录
        if (StringUtils.isNotBlank(dto.getPhone())&&StringUtils.isNotBlank(dto.getPassword())){
            //1.1 通过手机号查询用户信息
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone,dto.getPhone());
            ApUser apUser = getOne(queryWrapper);
            //1.2 如没有用户信息
            if (apUser==null){
                throw new LeadException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //1.3 验证密码
            boolean b = encoder.matches(dto.getPassword(), apUser.getPassword());
            if (!b) {
                throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            result.put("user", BeanHelper.copyProperties(apUser, UserInfoDto.class));
            userId = apUser.getId();
        }else {
            //2. 如果是设备登陆，生成token
            if (StringUtils.isBlank(dto.getEquipmentId())){
                throw new LeadException(AppHttpCodeEnum.PARAM_INVALID);
            }
        }
        //3. 生成token
        String tokenExpireInMinutes = JwtUtils.generateTokenExpireInMinutes(userId, 120);
        result.put("token",tokenExpireInMinutes);
        return result;
    }
}
